<template>
  <div style="padding:15px;">
    <el-form ref="queryFrom" :inline="true" :model="queryFrom" class="demo-form-inline">
      <el-form-item prop="code">
        <el-input v-model="queryFrom.code" class="el-input--mini" placeholder="菜单编码" />
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="queryFrom.name" class="el-input--mini" placeholder="菜单名" />
      </el-form-item>
      <el-form-item prop="status">
        <el-select v-model="queryFrom.status" clearable placeholder="状态" class="el-input--mini">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select></el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-search" @click="queryData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-delete" @click="onReset('queryFrom')">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-plus" @click="onAddParnetMenu">新增菜单</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :row-style="{height:'10px'}"
      :cell-style="{padding:'0px'}"
    >
      <el-table-column
        prop="id"
        label="ID"
        sortable
        width="100"
      />
      <el-table-column
        prop="name"
        label="菜单名称"
        width="180"
      />
      <el-table-column
        prop="icon"
        label="icon"
        width="80"
      >
        <template slot-scope="scope">
          <i :class="scope.row.icon" style="font-size: 25px;font-weight: bold;" />
        </template>
      </el-table-column>
      <el-table-column
        prop="code"
        label="code"
        width="180px"
      />
      <el-table-column
        prop="uri"
        label="组件路径"
        width="140px"
      />
      <el-table-column prop="status" align="center" label="状态" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusTagFilter">
            {{ scope.row.status | statusfilters }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" align="center" label="创建时间" width="210px" sortable>
        <template slot-scope="scope">
          <p>{{ scope.row.createTime | timefilters }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="updatedTime" align="center" label="修改时间" width="210px" sortable>
        <template slot-scope="scope">
          <p>{{ scope.row.updateTime | timefilters }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作" align="center">
        <template slot-scope="scope">
          <div>
            <el-button class="el-button--mini" size="small" icon="el-icon-edit" @click="onEdit(scope.row)">编辑</el-button>
            <el-button class="el-button--mini" type="primary" size="small" icon="el-icon-plus" @click="onAdd(scope.row)">添加</el-button>
            <el-button class="el-button--mini" :type="scope.row.status | editStatusTagFilter" size="small" icon="el-icon-close" @click="forbiddenUser(scope.row)">{{ scope.row.status ==1? '禁用':'启用' }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :total="page.totalCount"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="50"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      v-loading="dialogLoading"
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      element-loading-text="拼命加载中"
      :close-on-click-modal="false"
      :before-close="closeDialog"
      :show-close="false"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
      >
        <div v-if="!add">
          <el-form-item v-show="isAdd" label="上级菜单" :label-width="formLabelWidth" prop="parnetName">
            <el-input
              v-model="parnetName"
              autocomplete="off"
              maxlength="20"
              :disabled="true"
              class="el-input--medium"
            />
          </el-form-item>
        </div>
        <el-form-item label="菜单名称" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="editForm.name"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            prefix-icon="el-icon-edit"
            class="el-input--medium"
          />
        </el-form-item>
        <el-form-item label="菜单CODE" :label-width="formLabelWidth" prop="code">
          <el-input
            v-model="editForm.code"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            prefix-icon="el-icon-paperclip"
            class="el-input--medium"
          />
        </el-form-item>
        <el-form-item label="菜单状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="editForm.status" name="editSex" placeholder="角色状态" clearable prefix-icon="el-icon-paperclip" class="el-input--medium">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="隐藏/展示" :label-width="formLabelWidth" prop="isHide">
          <el-select v-model="editForm.isHide" name="isHide" placeholder="页面隐藏/展示" clearable prefix-icon="el-icon-paperclip" class="el-input--medium">
            <el-option
              v-for="item in hideOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单路径" :label-width="formLabelWidth" prop="url">
          <el-input
            v-model="editForm.url"
            autocomplete="off"
            maxlength="50"
            show-word-limit
            prefix-icon="el-icon-s-promotion"
            class="el-input--medium"
          />
        </el-form-item>
        <el-form-item label="菜单icon" :label-width="formLabelWidth" prop="icon">
          <el-input
            v-model="editForm.icon"
            autocomplete="off"
            maxlength="25"
            show-word-limit
            prefix-icon="el-icon-eleme"
            class="el-input--medium"
          />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--mini" @click="cancelChange('editForm')">取 消</el-button>
        <el-button class="el-button--mini" type="primary" @click="onSubmitMenu('editForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryAuthorityMenuByPage, updateMenuInfo, saveResource } from '@/api/system/resource'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    timefilters(val) {
      if (val == null || val === '') {
        return '暂无时间'
      } else {
        const d = new Date(val) // val 为表格内取到的后台时间
        const month =
          d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
        const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
        const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
        const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
        const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
        const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec
        return times
      }
    },
    statusfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '正常'
        }
        if (val === 9) {
          return '禁用'
        }
        if (val === 3) {
          return '删除'
        }
        if (val === 4) {
          return '非法'
        }
      }
    },
    statusTagFilter(val) {
      const statusMap = {
        '1': 'success',
        '2': 'info',
        '3': 'danger',
        '4': 'danger'
      }
      return statusMap[val]
    },
    editStatusTagFilter(val) {
      const statusMap = {
        '1': 'warning',
        '9': 'success'
      }
      return statusMap[val]
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      dialogLoading: true,
      dialogTitle: '',
      formLabelWidth: '100px',
      options: [{
        value: 1,
        label: '正常'
      }, {
        value: 9,
        label: '禁用'
      }],
      hideOptions: [{
        value: 1,
        label: '隐藏'
      }, {
        value: 0,
        label: '展示'
      }],
      queryFrom: {
        code: '',
        name: '',
        status: ''
      },
      page: {
        'rowCount': 10,
        'currentPage': 1,
        'pageSize': 40,
        'pageCount': 2,
        'totalCount': 0,
        'orderBy': null,
        'outofBounds': false,
        'limitStart': 0
      },
      rules: {
        name: [{ required: true, message: '请填写菜单名称', trigger: 'blur' }],
        code: [{ required: true, message: '请填写菜单code', trigger: 'blur' }],
        status: [{ required: true, message: '请选择菜单状态', trigger: 'blur' }],
        isHide: [{ required: true, message: '请选择菜单隐藏/展示', trigger: 'blur' }],
        icon: [{ required: true, message: '请填写菜单icon', trigger: 'blur' }],
        url: [{ required: true, message: '请填写菜单组件路径', trigger: 'blur' }]

        // resourceList: [{ required: true, message: '请选中可用菜单', trigger: 'blur' }]
      },
      tableData: [],
      editForm: {
        id: '',
        name: '',
        url: '',
        icon: '',
        status: '',
        code: '',
        isHide: ''

      },
      isAdd: false,
      parnetName: '',
      parnetId: '',
      add: false

    }
  },
  created() {
    this.queryData()
  },
  methods: {
    queryData() {
      this.clear()
      const queryPage = { page: this.page }
      var qq = Object.assign(queryPage, this.queryFrom)
      queryAuthorityMenuByPage(qq).then(response => {
        const menus = response.data.menu
        menus.forEach((p) => {
          this.tableData.push({
            id: p.id,
            name: p.name,
            code: p.code,
            status: p.status,
            createTime: p.createTime,
            updateTime: p.updateTime,
            icon: p.icon,
            uri: p.uri,
            children: p.children,
            hasChildren: true,
            isHide: p.isHide

          })
        })
        this.page = response.data.page
      })
    },
    load(tree, treeNode, resolve) {
      const tr = []
      tree.children.forEach((p) => {
        if (p.children !== null && p.children.length > 0) {
          tr.push({
            id: p.id,
            name: p.name,
            code: p.code,
            status: p.status,
            createTime: p.createTime,
            updateTime: p.updateTime,
            icon: p.icon,
            uri: p.uri,
            children: p.children,
            hasChildren: true,
            isHide: p.isHide
          })
        } else {
          tr.push({
            id: p.id,
            name: p.name,
            code: p.code,
            status: p.status,
            createTime: p.createTime,
            updateTime: p.updateTime,
            icon: p.icon,
            uri: p.uri,
            hasChildren: false,
            isHide: p.isHide
          })
        }
      })
      resolve(tr)
    },
    onEdit(row) {
      this.isAdd = false
      this.dialogFormVisible = true
      this.dialogLoading = false
      this.dialogTitle = '编辑菜单'
      this.editForm.name = row.name
      this.editForm.code = row.code
      this.editForm.icon = row.icon
      this.editForm.status = row.status
      this.editForm.url = row.uri
      this.editForm.id = row.id
      this.editForm.isHide = row.isHide
    },
    onAdd(row) {
      this.isAdd = true
      this.parnetName = row.name
      this.parnetId = row.id
      this.dialogFormVisible = true
      this.dialogLoading = false
      this.dialogTitle = '添加菜单'
      this.editForm.id = ''
      this.editForm.name = ''
      this.editForm.status = ''
      this.editForm.code = ''
      this.editForm.url = ''
      this.editForm.icon = ''
      this.editForm.isHide = ''
    },
    onAddParnetMenu() {
      this.isAdd = true
      this.add = true
      this.dialogFormVisible = true
      this.dialogLoading = false
      this.dialogTitle = '添加菜单'
      this.editForm.id = ''
      this.editForm.name = ''
      this.editForm.status = ''
      this.editForm.code = ''
      this.editForm.url = ''
      this.editForm.icon = ''
    },
    forbiddenUser(row) {
      this.editForm.id = row.id
      this.editForm.name = row.name
      this.editForm.status = row.status === 1 ? 9 : 1
      this.editForm.code = row.code
      this.editForm.url = row.url
      this.editForm.icon = row.icon
      const title = row.status === 1 ? '禁用' : '启用'
      this.$confirm('确认要' + title + '该菜单: ' + row.name + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateMenuInfo(this.editForm).then(response => {
          this.$notify({ title: response.msg, duration: 1000, type: 'success' })
          this.clear()
          this.queryData()
        })
      }).catch(() => {
      })
    },
    onSubmitMenu(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          if (!this.isAdd) {
            updateMenuInfo(this.editForm).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.clear()
              this.queryData()
            })
          } else {
            var query = { 'parnetId': this.parnetId }
            var qq = Object.assign(query, this.editForm)
            saveResource(qq).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.clear()
              this.queryData()
            })
          }
        } else {
          return false
        }
        this.$refs[formName].clearValidate()
      })
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
    }, handleSizeChange(val) {
      this.page.pageSize = val
      this.queryData()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.queryData()
    },
    clear() {
      this.dialogFormVisible = false
      this.tableData = []
      this.editForm.id = ''
      this.editForm.name = ''
      this.editForm.status = ''
      this.editForm.code = ''
      this.editForm.url = ''
      this.editForm.icon = ''
      this.editForm.isHide = null
      this.add = false
      this.parnetId = ''
    },
    cancelChange(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].clearValidate()
    },
    closeDialog() {
      this.cancelChange()
    }
  }
}
</script>
